from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth import get_user_model


class UserManager(BaseUserManager):
    def _create_user(self, telphone, username, password, **kwargs):
        if not telphone:
            raise ValueError('请输入手机号')
        if not password:
            raise ValueError('请输入密码')
        user = self.model(telphone=telphone, username=username, **kwargs)
        user.set_password(password)
        user.save()
        return user

    # TODO: 创建普通用户
    def create_user(self, telphone, username, password, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user(telphone, username, password, **kwargs)

    # TODO: 创建管理员用户
    def create_superuser(self, telphone, username, password, **kwargs):
        kwargs['is_superuser'] = True
        return self._create_user(telphone, username, password, **kwargs)


# TODO 3.继承自AbstractUser
# class User(AbstractUser):
#     telphone = models.CharField(max_length=11, unique=True)
#     school = models.CharField(max_length=100)
#
#     # 指定telephone作为USERNAME_FIELD，以后使用authenticate函数验证的时候，就可以根据telephone来验证
#     # 而不是原来的username
#     USERNAME_FIELD = 'telphone'
#
#     # 重新定义Manager对象，在创建user的时候使用telephone和password，而不是使用username和password
#     objects = UserManager()


# TODO 4.继承自AbstractBaseUser模型
class User(AbstractBaseUser, PermissionsMixin):
    telphone = models.CharField(max_length=11, unique=True)
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)

    # 指定telephone作为USERNAME_FIELD，以后使用authenticate函数验证的时候，就可以根据telephone来验证
    # 而不是原来的username
    USERNAME_FIELD = 'telphone'

    # 一个字段名列表，用于当通过createsuperuser管理命令创建一个用户时的提示。
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username


class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='articles')
